package edu.dali.enterprise_test.service.product.impl;

import com.github.pagehelper.Page;
import edu.dali.enterprise_test.dao.mapper.product.ProductMapper;
import edu.dali.enterprise_test.exception.UploadException;
import edu.dali.enterprise_test.model.Pager;
import edu.dali.enterprise_test.model.dto.DetailInfo;
import edu.dali.enterprise_test.model.dto.InvoiceEntity;
import edu.dali.enterprise_test.model.vo.Dto;
import edu.dali.enterprise_test.service.product.ProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

//    @Autowired
//    private SaleMapper saleMapper;

    @Override
    public Pager<Dto> getData(Dto dto) {
        Pager<Dto> p = new Pager<>();
        List<Dto> data = productMapper.getProduct(dto);
        p.setData(data);
        int count = (int)((Page) data).getTotal();
        p.setCount(count);
        p.setMsg("");
        p.setCode(0);

        return p;
    }

    @Override
    public Dto getProductById(Dto dto) {
        return productMapper.getProductById(dto);
    }

    @Override
    public void addProduct(Dto dto) {
        productMapper.addProduct(dto);
    }

    @Override
    public void deleteProduct(String id) {
        productMapper.deleteProduct(id);
    }

    @Override
    public void updateProduct(Dto dto) {
        productMapper.updateProduct(dto);
    }

    @Override
    public List<Dto> productList(Dto dto) {
        return productMapper.productList(dto);
    }

    @Override
    public Map<String, Object> productStockInfo(InvoiceEntity invoiceEntity) {
        Map<String , Object> map = new HashMap<>();
        List<DetailInfo> details = invoiceEntity.getDetailInfoList();
        String info = "";
        boolean flag = true;
        List<Dto> substractStock = new ArrayList<>();
        List<Dto> sales = new ArrayList<>();
        for (DetailInfo detail : details) {
            String pid = detail.getId();
            BigDecimal quantity = detail.getSl();
            Dto param = new Dto();
            param.put("id" ,pid);
            Dto product = productMapper.getProductById(param);
            if(product.getAsInt("stock") < quantity.intValue()) {
                flag =false;
                info += product.getAsString("spmc")+"库存不足";
            }
            Dto stockDto = new Dto();
            stockDto.put("billno" , invoiceEntity.getBillno());
            stockDto.put("id" , pid);
            stockDto.put("quantity" , quantity.intValue());

            Dto sale = new Dto();
            sale.put("billno" , invoiceEntity.getBillno());
            sale.put("billindex" , detail.getBillindex());
            sale.put("productid" , pid);
            sale.put("sl" ,quantity.intValue());
            sale.put("storeno" , invoiceEntity.getStoreno());
            sale.put("amount" , detail.getJe());
            sales.add(sale);
            substractStock.add(stockDto);
        }
        if (flag) {
            for (int i = 0; i < substractStock.size(); i++) {
//                saleMapper.insertSale(sales.get(i));
                productMapper.reduceStock(substractStock.get(i));
            }
//            for (Dto s : substractStock) {
//                productMapper.reduceStock(s);
//            }
            map.put("code" , 0);
            map.put("msg" , "库存充足");
        } else {
            map.put("code" , 1);
            map.put("msg" , info);
        }

        return map;
    }

    @Override
    public int queryStock(String id) {
        return productMapper.queryStock(id);
    }

    @Override
    public void reduceStock(Dto dto) {
        productMapper.reduceStock(dto);
    }

    @Override
    public Map<String , Object> queryStockByIds(Map<String, Object> param) {
        Map<String , Object> map = new HashMap<>();
        List<Dto> list = productMapper.queryStockByIds(param);

        List<String> pids = new ArrayList<>();
        for (Dto d : list) {
            pids.add(d.getAsString("productid"));
        }
        map.put("pid" , pids);
        return map;
    }

    @Override
    public void insertProducts(List<Map<String, String>> datas) throws UploadException {
        int i = 0;
        for (Map<String , String> data : datas) {
            Dto dto = new Dto();
            i++;
            String error = "";
            if(!StringUtils.isEmpty(data.get("商品代码")))
                dto.put("qid" , data.get("商品代码"));
            else
                error += "第"+i+"行商品代码字段不存在 ";
            if(!StringUtils.isEmpty(data.get("商品名称")))
                dto.put("spmc" , data.get("商品名称"));
            else
                error += "第"+i+"行商品名称字段不存在 ";

            if(!StringUtils.isEmpty(data.get("规格型号"))) {
                dto.put("ggxh" , data.get("规格型号"));
            } else{
//                error += "第"+i+"行规格型号字段不存在 ";
                dto.put("ggxh" , "");
            }

            if(!StringUtils.isEmpty(data.get("单位")))
                dto.put("jldw" , data.get("单位"));
            else
                error += "第"+i+"行单位字段不存在 ";
            if(!StringUtils.isEmpty(data.get("汇通总库数量"))) {
                String msl  = data.get("汇通总库数量");
                if(!StringUtils.isNumeric(msl)) {
                    error += "第"+i+"行汇通总库存数不为数字";
                }
                dto.put("stock" , msl);
            }
            else {
                error += "第"+i+"行汇通总库数量字段不存在 ";
            }
            if(!StringUtils.isEmpty(data.get("税收编码")))
                dto.put("spbm" , StringUtils.rightPad(data.get("税收编码") ,19 ,'0'));
            else
                error += "第"+i+"行税收编码字段不存在 ";

            if (!StringUtils.isEmpty(error))
                throw new UploadException(error);
            int count = productMapper.queryStockByQid(dto);


            if (count > 0) {
                productMapper.increaseStcok(dto);
            } else {
                productMapper.addProduct(dto);
            }

        }
    }
}
